package org.blame.lotterysystem.service.impl;

import org.blame.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import org.blame.lotterysystem.common.exception.ServiceException;
import org.blame.lotterysystem.service.PictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;


@Service
public class PictureServiceImpl implements PictureService {

    @Value(("${pic.local-path}"))
    private String picLocalPath;

    @Override
    public String savePicture(MultipartFile pic) {
//        判断是否有该路径，如果没有自动创建
        File dir=new File(picLocalPath);
        if(!dir.exists()){
            dir.mkdirs();
        }

//        获得照片的文件全称
        String fileName=pic.getOriginalFilename();

//        增加断言，如果为空就抛出异常
        assert fileName !=null;

//        截取后缀，例如.jpg
        String suffixName=fileName.substring(fileName.lastIndexOf("."));
//        生成一个随机的UUID作为文件明，然后再加上后缀
        fileName= UUID.randomUUID()+suffixName;
        try {

//            进行图片的保存
            pic.transferTo(new File(picLocalPath + "/" +fileName));
        } catch (IOException e) {
            throw new ServiceException(ServiceErrorCodeConstants.PICTURE_UPLOAD_ERROR);
        }
        return fileName;
    }
}